package agents.profileragentbehaviuors;

import java.io.IOException;
import resource.UserProfile;
import agents.ProfilerAgent;
import jade.core.AID;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class GetTourFromGuideBehaviour extends Behaviour {
	boolean hasSentMessageToGuide = false;
	AID tourGuide;
	ProfilerAgent owner;
	UserProfile user;
	boolean done = false;
	
	public GetTourFromGuideBehaviour(UserProfile user, ProfilerAgent owner){
		this.user = user;
		this.owner = owner;
	}
	
	@Override
	public void action() {
		tourGuide = owner.getTourGuide();
		
		if(!hasSentMessageToGuide){
			ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
			message.addReceiver(tourGuide);
			try {
				message.setContentObject(user);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			owner.send(message);
			hasSentMessageToGuide = true;
		}
		
		MessageTemplate template = MessageTemplate.MatchPerformative(ACLMessage.INFORM);
		ACLMessage msg = owner.receive(template);
		if (msg != null) {
			try {
				owner.setTour((String[]) msg.getContentObject());
				done = true;
			} catch (UnreadableException e) {
				throw new RuntimeException(e);
			}
		}
		else {
			block();
		}			
	}

	@Override
	public boolean done() {
		return done;
	}

}
